package com.kzw.web;

import java.util.Date;

import com.kzw.entity.Article;
import com.kzw.entity.User;
import com.kzw.service.ArticleService;

import my.bean.Msg;
import my.db.Page;
import my.mvc.Annotation.JSON;
import my.mvc.RequestContext;
import my.util.BeanUtil;

@SuppressWarnings("unchecked")
public class ArticleAction {

	private ArticleService service = new ArticleService();

	/**
	 * 文章列表
	 * */
	@JSON
	public Page<Article> list(RequestContext rc) {
		// 获得分页信息, layui表格分页参数：page、limit
		Page<Article> page = rc.form(Page.class);
		String title = rc.param("title");
		service.list(page, title);		
		return page;
	}
	
	/**
	 * 保存
	 * */
	@JSON
	public Msg save(RequestContext rc) throws Exception {
		User user = (User)rc.sessionAttr("USER");
		Article a = rc.form(Article.class);
		if(a.getId() == 0) {
			if(a.getCtime() == null) {
				a.setCtime(new Date());
			}
			a.setAuthor(user.getUname());
			a.setAuthorId(user.getId());
			service.save(a);
		} else {
			Article orgA = service.get(a.getId());
			BeanUtil.copyNotNullProperties(orgA, a);
			service.update(orgA);
		}
		
		return new Msg(true);
	}
	
	/**
	 * 获得文章
	 * */
	public void get(RequestContext rc) {
		long id = rc.param("id", 0L);
		Article article = service.get(id);
		rc.reqAttr("article", article);
		rc.forward("/page/blog/article_form.jsp");
	}
}
